package com.atguigu.service.impl;

import cn.hutool.core.date.DateUtil;
import com.atguigu.client.AlbumFeignClient;
import com.atguigu.client.UserFeignClient;
import com.atguigu.constant.SystemConstant;
import com.atguigu.entity.*;
import com.atguigu.mapper.UserInfoMapper;
import com.atguigu.result.RetVal;
import com.atguigu.service.*;
import com.atguigu.vo.UserInfoVo;
import com.atguigu.vo.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.client.utils.DateUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Joe
 * @since 2024-11-14
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserPaidTrackService userPaidTrackService;
    @Autowired
    private UserPaidAlbumService userPaidAlbumService;

    //获取用户是否需要购买的标识
    @Override
    public Map<Long, Boolean> getUserShowPaidMarkOrNot(Long albumId, List<Long> needPayTrackIdList) {
        HashMap<Long, Boolean> showPaidMarkMap = new HashMap<>();
        //查询用户购买过的专辑
        LambdaQueryWrapper<UserPaidAlbum> wrapper = new LambdaQueryWrapper<>();
        //Long userId = AuthContextHolder.getUserId();
        Long userId = 15l;
        wrapper.eq(UserPaidAlbum::getUserId,userId);
        wrapper.eq(UserPaidAlbum::getAlbumId,albumId);
        UserPaidAlbum userPaidAlbum = userPaidAlbumService.getOne(wrapper);
        if(userPaidAlbum != null){
            //用户购买过该专辑，不需要购买
            needPayTrackIdList.forEach(trackId->{
                showPaidMarkMap.put(trackId,false);
            });
            return showPaidMarkMap;
        }else {
            //用户购买过的声音
            LambdaQueryWrapper<UserPaidTrack> paidTrackWrapper = new LambdaQueryWrapper<>();
            paidTrackWrapper.eq(UserPaidTrack::getUserId,userId);
            paidTrackWrapper.in(UserPaidTrack::getTrackId,needPayTrackIdList);
            //查询出已经支付过的支付列表
            List<UserPaidTrack> userPaidTrackList = userPaidTrackService.list(paidTrackWrapper);
            List<Long> paidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
            needPayTrackIdList.forEach(trackId->{
                if(paidTrackIdList.contains(trackId)) {//用户购买过该声音，不需要购买
                    showPaidMarkMap.put(trackId,false);
                }else {
                    //未购买，需要显示购买图标
                    showPaidMarkMap.put(trackId,true);
                }
            });
            return showPaidMarkMap;
        }
    }

    @Autowired
    private AlbumFeignClient albumFeignClient;
    @Autowired
    private UserVipInfoService userVipInfoService;
    @Autowired
    private VipServiceConfigService vipServiceConfigService   ;
    @Override
    public void updateUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {

        //如果购买的是专辑
        if(userPaidRecordVo.getItemType().equals(SystemConstant.BUY_ALBUM)){
            long count = userPaidAlbumService.count(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getOrderNo, userPaidRecordVo.getOrderNo()));
            if(count > 0){
                return;
            }
            UserPaidAlbum userPaidAlbum = new UserPaidAlbum();
            userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
            userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));
            userPaidAlbum.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidAlbumService.save(userPaidAlbum);
        }else if(userPaidRecordVo.getItemType().equals(SystemConstant.BUY_TRACK)){
            //如果购买的是声音
            long count = userPaidTrackService.count(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo()));
            if(count > 0){
                return;
            }
            TrackInfo trackInfo = albumFeignClient.getTrackInfoById(userPaidRecordVo.getItemIdList().get(0)).getData();
            List<UserPaidTrack> userPaidTrackList = userPaidRecordVo.getItemIdList().stream().map(trackId -> {
                UserPaidTrack userPaidTrack = new UserPaidTrack();
                userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                userPaidTrack.setTrackId(trackId);
                userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                return userPaidTrack;
            }).collect(Collectors.toList());
            userPaidTrackService.saveBatch(userPaidTrackList);
        }else if(userPaidRecordVo.getItemType().equals(SystemConstant.BUY_VIP)){
             //如果购买的是VIP
            Long vipConfigId = userPaidRecordVo.getItemIdList().get(0);
            VipServiceConfig vipConfig = vipServiceConfigService.getById(vipConfigId);



            UserVipInfo userVipInfo = new UserVipInfo();
            userVipInfo.setUserId(userPaidRecordVo.getUserId());
            userVipInfo.setOrderNo(userPaidRecordVo.getOrderNo());
            //拿到用户信息
            UserInfo userInfo = getById(userPaidRecordVo.getUserId());
            Date startTime = new Date();
            //判断当前用户是否为VIP，如果用户是VIP并且没有过期，VIP时间要累加
            if(userInfo.getIsVip()==1&&userInfo.getVipExpireTime().after(new Date())){
                startTime = userInfo.getVipExpireTime();
            }

            Date newExpireTime = new DateTime(new Date()).plusMonths(vipConfig.getServiceMonth()).toDate();
            userVipInfo.setStartTime(startTime);
            userVipInfo.setExpireTime(newExpireTime);
            userVipInfoService.save(userVipInfo);
            //更新VIP信息
            userInfo.setIsVip(1);
            userInfo.setVipExpireTime(newExpireTime);
            updateById(userInfo);
        }
    }

    //更新VIP到期失效状态
    @Override
    public void updateVipExpireStatus() {
        //1.找出已经过期会员
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.lt(UserInfo::getVipExpireTime, DateUtil.beginOfDay(new Date()));
        wrapper.eq(UserInfo::getIsVip,"1");
        List<UserInfo> userList = this.list(wrapper);
        //2.批量更新
        if(CollectionUtils.isEmpty(userList)){
            List<UserInfo> collect = userList.stream().map(userInfo -> {
                UserInfo userInfo1 = new UserInfo();
                userInfo1.setId(userInfo.getId());
                userInfo1.setIsVip(0);
                return userInfo1;
            }).collect(Collectors.toList());
            this.updateBatchById(collect);
        }
    }
}
